package com.aicoq.example.utils.http;

import okhttp3.*;

import java.io.IOException;
import java.util.Objects;

public class OkHttpUtils {

    public static String post(String url, String body) {
        var client = new OkHttpClient.Builder().build();
        var mediaType = MediaType.parse("application/json; charset=utf-8");

        var requestBody = RequestBody.Companion.create(body, mediaType);
        var request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try {
            try (var response = client.newCall(request).execute()) {
                var responseBody = response.body();
                if (Objects.nonNull(responseBody)) {
                    return responseBody.string();
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "";
    }

    public static String get(String url) {
        var client = new OkHttpClient.Builder().build();
        var request = new Request.Builder()
                .url(url)
                .get()
                .build();
        try {
            try (var response = client.newCall(request).execute()) {
                var responseBody = response.body();
                if (Objects.nonNull(responseBody)) {
                    return responseBody.string();
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "";
    }

}
